package jp.co.sharp.android.parents.kidsguard.activity.edit;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.PowerSettingActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.QuickDispatchSettingActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.SettingActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

public class AlarmActivity extends AppCompatActivity {
    private ParentBleTransfer mParentBleTransfer;
    private App mApp;
    private KidInfoEntity mKidInfoEntity;
    private Button mSubmitBtn;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private DelDeviceConfirmDlg mDelDeviceConfirmDlg;
    private Map<Integer, Boolean> alterRecord = new HashMap<>();
    private Map<Integer, Boolean> checkedRecord = new HashMap<>();
    private JSONArray alarmList;
    private final String stateOn = "0";
    private final String stateOff = "1";
    private int mViewProcess = 0;

    private int endAlramId = -1;
    private final int REQUEST_CODE_ADD = 1;
    private final int REQUEST_CODE_EDIT = 2;
    private int mPageCode = PageSerialNumConstants.PAGE_SERIAL_ALARM_SETTING;
    private boolean SCREEN_OPERATE = false;
    private boolean subpageOn = false;
    private boolean mIsLoading = true;
    private boolean mKidReceiveFlag = false;
    private boolean mUnReceiver = true;
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    private static final String TAG = "TAG";
    // プログラムロック
    private String mSyncLock = "syncLock";
    // 編集を再開しています...
    private boolean mEditReopening = false;
    private static final int PAGE_EDIT_REOPEN = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "AlarmActivity_onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);
        // init
        mApp = (App) getApplication();
        mViewProcess = 0;
        initReceiver();
        mKidInfoEntity = mApp.findKidInfoBySelect();

        try {
            initActivity();
        } catch (JSONException e) {
            Log.e(TAG, e.getMessage());
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "AlarmActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    @Override
    protected void onStop() {
        Log.i(TAG, "AlarmActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onStop();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "AlarmActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if (mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT) {
                    Message msg = new Message();
                    msg.what = PAGE_EDIT_REOPEN;
                    handler.sendMessage(msg);
                }
                mSystemHomeFlag = false;
            }
            mUnReceiver = false;
        }
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "AlarmActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onDestroy();
    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        backActivity(null);
    }

    private void initActivity() throws JSONException {
        Log.i(TAG, "AlarmActivity_initActivity");
        TextView textView = (TextView)findViewById(R.id.settingSecondMenu);
        String strSecondMenu = mKidInfoEntity.getKidName() + "のキッズケータイ";
        textView.setText(strSecondMenu);
        mSubmitBtn = findViewById(R.id.submitBtn);
        mSubmitBtn.setEnabled(false);
        mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    for (int i = 0; i < alarmList.length(); i++) {
                        JSONObject alarm = alarmList.getJSONObject(i);
                        Integer id = Integer.valueOf(alarm.get("id").toString());
                        if (alterRecord.containsKey(id)) {
                            if (alterRecord.get(id)) {
                                alarm.put("state", Integer.valueOf(stateOn));
                            } else {
                                alarm.put("state", Integer.valueOf(stateOff));
                            }
                        }
                    }

                    // Dlg
                    String message = "キッズケータイへ反映中..";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(AlarmActivity.this, R.style.commonDlg, message, true);
                    mDealWithWaitingDlg.show();
                    // init
                    new BusinessThread(getSendSetRequestJson(), mParentBleTransfer, mKidInfoEntity).start();
                } catch (JSONException e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        });

        ImageView imageView = findViewById(R.id.addPeriodSetting);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openEditPage(endAlramId + 1, true, REQUEST_CODE_ADD);
            }
        });
        // Dlg
        String message = "キッズケータイから情報を取得しています...";
        mDealWithWaitingDlg = new DealWithWaitingDlg(AlarmActivity.this, R.style.commonDlg, message, true);
        mDealWithWaitingDlg.show();
        mViewProcess = Constants.SEND_KID_IS_USING;
        new BusinessThread(Constants.SEND_KID_IS_USING, mParentBleTransfer, mKidInfoEntity).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        initReceiver();
        if (resultCode == 200) {
            // Dlg
            String message = "キッズケータイから情報を取得しています...";
            mDealWithWaitingDlg = new DealWithWaitingDlg(AlarmActivity.this, R.style.commonDlg, message, true);
            mDealWithWaitingDlg.show();
            mViewProcess = Constants.SEND_KID_GET_INFO;
            new BusinessThread(getKidDataRequestJson(), mParentBleTransfer, mKidInfoEntity).start();
        }
        subpageOn = false;
    }

    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        // ロック画面
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        // 画面を開く
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                if (bluetoothReceiverDto.isFinished()) {
                    mKidReceiveFlag = true;
                    switch (mViewProcess) {
                        case Constants.SEND_KID_ENTER:
                            if (mIsLoading) {
                                mViewProcess = Constants.SEND_KID_GET_INFO;
                                new BusinessThread(getKidDataRequestJson(), mParentBleTransfer, mKidInfoEntity).start();
                            }else {
                                mEditReopening = false;
                            }
                            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                                mDealWithWaitingDlg.dismiss();
                            }
                            break;
                        case Constants.SEND_KID_EXIT:
                            if (null != mDelDeviceConfirmDlg && mDelDeviceConfirmDlg.isShowing()) {
                                mDelDeviceConfirmDlg.dismiss();
                            }
                            if (!SCREEN_OPERATE) {
                                AlarmActivity.this.finish();
                            }
                            break;
                    }
                }
            } else if (mKidReceiveFlag && RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                String retStr = bluetoothReceiverDto.getRetStr();
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(retStr);
                    System.out.println("铃声列表json：" + jsonObject);
                    if (RequestMethodConstants.METHOD_GET_ALARMS.equals(jsonObject.getString("method"))) {
                        if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                            mDealWithWaitingDlg.dismiss();
                        }
                        JSONArray dataList = jsonObject.getJSONArray("data");
                        alarmList = dataList;
                        LinearLayout main = findViewById(R.id.mainView);
                        main.removeAllViews();
                        for (int i = 0; i < dataList.length(); i++) {
                            JSONObject data = dataList.getJSONObject(i);
                            String time = data.getString("time");
                            String[] timeArr = time.split(":");
                            Integer hour = Integer.valueOf(timeArr[0]);
                            String prefix = "午前";
                            if (hour >= 12) {
                                prefix = "午後";
                                hour = Math.abs(hour - 12);
                            }
                            time = prefix + hour + ":" + timeArr[1];

                            Integer repetition = data.getInt("repetition");
                            StringBuffer contentText = new StringBuffer();
                            if (repetition > 0) {
                                List<String> repetitionList = repetitionToStirng(Integer.toHexString(repetition));
                                for (String week : repetitionList) {
                                    contentText.append(week);
                                    contentText.append(" ");
                                }
                            } else {
                                contentText.append("1回のみ");
                            }
                            boolean checked = false;
                            if (stateOn.equals(data.get("state").toString())) {
                                checked = true;
                            }
                            int id = data.getInt("id");
                            join(time, contentText.toString(), checked, id);
                            if (endAlramId < id) {
                                endAlramId = id;
                            }
                        }
                        handler.sendEmptyMessage(0);
                    } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(jsonObject.getString("method"))) {
                        if (jsonObject.getString("result").equals(Constants.ON_SYNC_RESULT) && !subpageOn) {
                            handler.sendEmptyMessage(0);
                            mViewProcess = Constants.SEND_KID_EXIT;
                            new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                        }
                    } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(jsonObject.getString("method"))) {
                        String message = "キッズケータイが操作されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(AlarmActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                AlarmActivity.this.finish();
                            }
                        });
                    } else if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(jsonObject.getString("method"))) {
                        if (jsonObject.getJSONObject("data").getString("state").equals(Constants.IS_USING_OK)) {
                            mViewProcess = Constants.SEND_KID_ENTER;
                            new BusinessThread(Constants.SEND_KID_ENTER, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                        } else {
                            handler.sendEmptyMessage(0);
                            String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(AlarmActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    AlarmActivity.this.finish();
                                }
                            });
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        }
    };

    private void join(String dateText, String contentText, boolean checked, Integer id) {
        LinearLayout main = findViewById(R.id.mainView);
        LinearLayout entry = new LinearLayout(AlarmActivity.this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getPixelsFromDp(360), getPixelsFromDp(72));
        entry.setLayoutParams(layoutParams);
        //text块
        LinearLayout example = new LinearLayout(AlarmActivity.this);
        entry.addView(example);
        LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(getPixelsFromDp(288), getPixelsFromDp(72));
        example.setLayoutParams(layoutParams2);
        example.setOrientation(LinearLayout.VERTICAL);
        example.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    openEditPage(id, false, REQUEST_CODE_EDIT);
                }
                return true;
            }
        });

        TextView textView1 = new TextView(AlarmActivity.this);
        textView1.setText(dateText);
        textView1.setTextSize(16);
        textView1.setTextColor(AlarmActivity.this.getResources().getColor(R.color.colorConnBtn));
        LinearLayout.LayoutParams layoutParams3 = new LinearLayout.LayoutParams(getPixelsFromDp(272), getPixelsFromDp(23));
        layoutParams3.setMargins(getPixelsFromDp(16), getPixelsFromDp(13), 0, 0);
        textView1.setLayoutParams(layoutParams3);
        textView1.setGravity(Gravity.FILL_VERTICAL);
        example.addView(textView1);
        TextView textView2 = new TextView(AlarmActivity.this);
        textView2.setText(contentText);
        textView2.setTextSize(14);
        textView2.setTextColor(AlarmActivity.this.getResources().getColor(R.color.colorConnBtn));
        textView2.setGravity(Gravity.FILL_VERTICAL);
        LinearLayout.LayoutParams textParams2 = new LinearLayout.LayoutParams(getPixelsFromDp(272), getPixelsFromDp(24));
        textParams2.setMargins(getPixelsFromDp(16), getPixelsFromDp(4), 0, 0);
        textView2.setLayoutParams(textParams2);
        example.addView(textView2);

        Switch sw = new Switch(AlarmActivity.this);
        LinearLayout.LayoutParams switchParams = new LinearLayout.LayoutParams(getPixelsFromDp(48), getPixelsFromDp(48));
        switchParams.setMargins(getPixelsFromDp(8), getPixelsFromDp(16), 0, 0);
        sw.setLayoutParams(switchParams);
        sw.setThumbDrawable(getDrawable(R.drawable.switch_custom_thumb_selector));
        sw.setTrackDrawable(getDrawable(R.drawable.switch_custom_track_selector));
        sw.setGravity(Gravity.CENTER_VERTICAL);
        sw.setChecked(checked);
        sw.setId(id);
        checkedRecord.put(id, checked);
        sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                System.out.println("id" + compoundButton.getId() + "现在是：" + b);
                int id = compoundButton.getId();
                boolean checked = checkedRecord.get(id);
                if (checked != b) {
                    alterRecord.put(id, b);
                } else {
                    alterRecord.remove(id);
                }
                if (alterRecord.size() > 0) {
                    mSubmitBtn.setEnabled(true);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                } else {
                    mSubmitBtn.setEnabled(false);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                }
            }
        });
        entry.addView(sw);
        entry.setId(Integer.valueOf(id));
        main.addView(entry);
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                synchronized (mSyncLock) {
                    mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                    SCREEN_OPERATE = true;
                    mViewProcess = Constants.SEND_KID_EXIT;
                    new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                }
            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                synchronized (mSyncLock) {
                    mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                    if (!mPageJumpFlag) {
                        Message msg = new Message();
                        msg.what = PAGE_EDIT_REOPEN;
                        handler.sendMessage(msg);
                    }
                }
            } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                synchronized (mSyncLock) {
                    mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                    mSystemHomeFlag = true;
                    SCREEN_OPERATE = true;
                    mViewProcess = Constants.SEND_KID_EXIT;
                    new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                }
            } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                // 初期化
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                String macAddress = bluetoothReceiverDto.getAddress();
                if (mApp.isMimamoriCheck(macAddress)) {
                    mApp.addmLsIsMimamori(macAddress);
                    mViewProcess = Constants.SEND_KID_EXIT;
                    new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                    // ページジャンプ
                    mPageJumpFlag = true;
                    Intent intent1 = new Intent();
                    intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                    intent1.setClass(AlarmActivity.this, HomeActivity.class);
                    startActivity(intent1);
                } else {
                    mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                    ((App) getApplication()).updateKidInfo(mKidInfoEntity);

                    String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                    ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(AlarmActivity.this, R.style.commonDlg, message);
                    processWarringDlg.show();
                    processWarringDlg.setOnOperateSetListener(() -> {
                        processWarringDlg.dismiss();
                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setClass(AlarmActivity.this, EditActivity.class);
                        startActivity(intent1);
                    });
                }
            }
        }
    };

    public void backActivity(View view) {
        if (alterRecord.size() > 0) {
            String message = "編集内容は保存されていません。編集内容を破棄して前の画面に戻りますか？";
            mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(AlarmActivity.this, R.style.commonDlg, message);
            mDelDeviceConfirmDlg.show();
            mDelDeviceConfirmDlg.setOnOperateSetListener(new DelDeviceConfirmDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    mViewProcess = Constants.SEND_KID_EXIT;
                    new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                }
            });
        } else {
            mViewProcess = Constants.SEND_KID_EXIT;
            new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
        }
    }

    private void openEditPage(int id, boolean isAdd, int requestCode) {
        subpageOn = true;
        mPageJumpFlag = true;
        Intent intent = new Intent();
        intent.setClass(AlarmActivity.this, AlarmEditActivity.class);
        intent.putExtra("isAdd", isAdd);
        intent.putExtra("alramId", id);
        intent.putExtra("alarmList", alarmList.toString());
        startActivityForResult(intent, requestCode);
    }

    private int getPixelsFromDp(int size) {

        DisplayMetrics metrics = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        return (size * metrics.densityDpi) / DisplayMetrics.DENSITY_DEFAULT;

    }

    public static List<String> repetitionToStirng(String repetition) {
        char[] split = repetition.toCharArray();
        List<String> list = new ArrayList<>();
        switch (split[split.length - 1]) {
            case '1':
                list.add("月");
                break;
            case '2':
                list.add("火");
                break;
            case '4':
                list.add("水");
                break;
            case '8':
                list.add("木");
                break;
            case '3':
                list.add("月");
                list.add("火");
                break;
            case '7':
                list.add("月");
                list.add("火");
                list.add("水");
                break;
            case 'f':
                list.add("月");
                list.add("火");
                list.add("水");
                list.add("木");
                break;
            case '6':
                list.add("火");
                list.add("水");
                break;
            case 'e':
                list.add("火");
                list.add("水");
                list.add("木");
                break;
            case 'c':
                list.add("水");
                list.add("木");
                break;
        }
        if (split.length > 1) {
            switch (split[split.length - 2]) {
                case '1':
                    list.add("金");
                    break;
                case '2':
                    list.add("土");
                    break;
                case '4':
                    list.add("日");
                    break;
                case '3':
                    list.add("金");
                    list.add("土");
                    break;
                case '7':
                    list.add("金");
                    list.add("土");
                    list.add("日");
                    break;
                case '6':
                    list.add("土");
                    list.add("日");
                    break;
            }
        }
        return list;
    }

    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            } else if (msg.what == PAGE_EDIT_REOPEN) {
                if (!mEditReopening) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(AlarmActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    SCREEN_OPERATE = true;
                    mViewProcess = Constants.SEND_KID_IS_USING;
                    new BusinessThread(Constants.SEND_KID_IS_USING,
                            mParentBleTransfer,
                            mKidInfoEntity,
                            null,
                            PageSerialNumConstants.PAGE_SERIAL_NUM_POWER_SETTING).start();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                    mEditReopening = true;
                }
            }
        }
    };


    private JSONObject getKidDataRequestJson() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("method", RequestMethodConstants.METHOD_GET_ALARMS);
            jsonObject.put("data", JSONObject.NULL);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return jsonObject;
    }

    private JSONObject getSendSetRequestJson() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("method", RequestMethodConstants.METHOD_SET_ALARMS);
            JSONObject jsonData = new JSONObject();
            jsonData.put("alarmList", alarmList);
            jsonObject.put("data", jsonData);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return jsonObject;
    }

}
